import { reactive, ref, onMounted, computed } from 'vue'
import testMp3 from '../../assets/test.mp3';
import { useStore }  from 'vuex';
import nextIcon from '@/assets/images/next.svg';
import prevIcon from '@/assets/images/prev.svg';
import './index.scss';

const Player = ({
    setup() {
        const audioRef = ref(null);
        const store = useStore();
        // 使用vuex
        const isMusicPlay = computed(() => {
            return store.state.isMusicPlay
        });
        // 本地状态
        const state = reactive({
            actionsSheetShow: false, // 弹窗出现
            isPlay: false, // 是否播放
            currentRate: 100, // 总进度
            rate: 0, // 播放进度
            timer: null, // 计时器
            audioDuration: 0, // 时长
            fullScreenShow: false, // 全屏
            currentTime: 0, // 正在播放
            allSec: '00:00', // 总时长
            curSec: '00:00', // 正在时长
        });

        // 修复v-model:show
        const actions = [
            {name: '选项一'},
            {name: '选项二'},
            {name: '选项三'},
        ];
        const onSelect = () => {
            // 默认情况下点击选项时不会自动收起
            // 可以通过 close-on-click-action 属性开启自动收起
            state.actionsSheetShow = false;
        };
        // 处理播放/暂停点击
        const handlePlayClick = () => {
            store.commit('handleChangeIsMusicPlay', !isMusicPlay.value);
            isMusicPlay.value ? audioRef.value.play() : audioRef.value.pause() ;
            audioListener();
            state.allSec = secondIntoMin(state.audioDuration);
        };
        // 监听音乐播放
        const audioListener = () => {
            if (isMusicPlay.value) {
                state.timer = setInterval(() => {
                    try {
                        state.currentTime = audioRef.value.currentTime;
                        const rate = parseInt(audioRef.value.currentTime / audioRef.value.duration * 100);
                        state.rate = rate;
                        state.curSec = secondIntoMin(state.currentTime);
                        if (rate === 100) {
                            clearInterval(state.timer);
                            state.rate = 0;
                            state.curSec = '00:00';
                            store.commit('handleChangeIsMusicPlay', false);
                        }
                    } catch (e) {
                        clearInterval(state.timer);
                    }
                }, 1000)
            } else {
                // state.rate = 0;
                // state.curSec = '00:00';
                clearInterval(state.timer);
            }
        };
        // 点击弹窗
        const sheetClose = () => {
            state.actionsSheetShow = false;
        };
        // 拖动前, 去掉计时器解决卡顿问题
        const handleSliderChangeStar = () => {
            clearInterval(state.timer);
        };
        // 进度拖动
        const handleSliderChange = (value) => {
            audioRef.value.currentTime = Math.ceil(state.audioDuration * value / 100);
            state.currentTime = audioRef.value.currentTime;
            state.curSec = secondIntoMin(state.currentTime);
        };
        // 进度拖动结束
        const handleSliderChangeEng = () => {
            audioListener();
        };
        // 秒转分秒
        const secondIntoMin = (SECONDS) => {
            let allMin = Math.floor(SECONDS / 60);
            let allSec = Math.floor(SECONDS) - allMin * 60; 
            allMin = allMin >= 10 ? allMin : '0' + allMin ;
            allSec = allSec >= 10 ? allSec : '0' + allSec;
            return `${allMin}:${allSec}`
        };
        // 生命周期: 安装
        onMounted(() => {
            audioRef.value.load();
            audioRef.value.oncanplay = () => {
                state.audioDuration = audioRef.value.duration;
            };
        });
        // 渲染圆形进度条
        const renderCircle = () => {
            const renderWhichPlayStatus = isMusicPlay.value ?
                <van-icon onClick={handlePlayClick} color='#d44439' name="pause" size="22"/>
                : <van-icon onClick={handlePlayClick} color='#d44439' name="play" size="22"/>;
            return (
                <van-circle
                    v-model={[state.currentRate, 'current-rate']}
                    rate={state.rate} layer-color="#ebedf0"
                    size="32"
                    color="#d44439"
                    stroke-width="60"
                    v-slots={{
                        'default': () => renderWhichPlayStatus
                    }}
                />
            )
        };
        // 渲染mini播放器
        const renderMiniPlay = () => (
            <div className='miniPlay'>
                {/*图片: 点击切花全屏播放器*/}
                <div className="icon" onClick={() => state.fullScreenShow = true}>
                    <div className="imgWrapper">
                        <img className={ isMusicPlay.value ? 'play' : 'play pause'}
                             src="http://p4.music.126.net/FJWZe1aQV2-iuYeq8gUR5A==/19022650672277889.jpg"
                             width="40" height="40" alt="img"/>
                    </div>
                </div>
                <div className="text">
                    <div className="name">Out of Love</div>
                    <div className="desc">Peter Manos</div>
                </div>
                <div className='console'>
                    <div>
                        {renderCircle()}
                    </div>
                    <div>
                        <van-icon name="wap-nav" size="29" color="#d44439" onClick={() => {
                            state.actionsSheetShow = true
                        }}/>
                    </div>
                </div>
            </div>
        );
        // 渲染全屏播放器
        const renderFullScreenPlayer = () => (
            <van-popup
                position={'bottom'}
                style={{height: '100%', width: '100%'}}
                v-model={[state.fullScreenShow, "show"]}
            >
                <div className="fullScreenPage">
                    <van-nav-bar
                        duration={0.05}
                        close-on-popstate
                        title="Out of Love"
                        v-slots={{
                            'left': () => <van-icon
                                onClick={ () => state.fullScreenShow = false }
                                color="#2e3030"
                                size={24} name="arrow-down"/>
                        }}
                    />
                    <div className="layer"/>
                    <h3 className="subtitle">Peter Manos</h3>
                    <div className="cd ">
                        <img
                            className={ isMusicPlay.value ? 'play' :  'play pause' }
                            src="http://p4.music.126.net/FJWZe1aQV2-iuYeq8gUR5A==/19022650672277889.jpg" alt=""/>
                    </div>
                    <div className="pageBottom">
                        <div className="progressBox">
                            <div className="time l">{state.curSec}</div>
                            <van-slider
                                buttonSize={18}
                                inactive-color="#404142"
                                active-color="#c32d2b"
                                v-model={state.rate}
                                onChange={handleSliderChange}
                                onDragStart={handleSliderChangeStar}
                                onDragEnd={handleSliderChangeEng}
                            />
                            <div className="time r">{state.allSec}</div>
                        </div>
                        <div className="controls">
                            <div>
                                <van-icon name="sort" color="#2E3030" size={30}/>
                            </div>
                            <div className="iconSize">
                                <img src={prevIcon} alt=""/>
                            </div>
                            <div>
                                {isMusicPlay.value ?
                                    <van-icon name="pause" onClick={handlePlayClick}  color="#2E3030" size={40} />
                                    :
                                    <van-icon name="play" onClick={handlePlayClick} color="#2E3030" size={40} />
                                }
                            </div>
                            <div className="iconSize">
                                <img src={nextIcon} alt=""/>
                            </div>
                            <div>
                                <van-icon name="wap-nav" color="#2E3030" size={30}/>
                            </div>
                        </div>
                    </div>
                </div>
            </van-popup>
        );
        // 最终渲染
        return () => (
            <>
                {renderMiniPlay()}
                {renderFullScreenPlayer()}
                <van-action-sheet
                    v-model={[state.actionsSheetShow, "show"]}
                    onSelect={onSelect}
                    actions={actions}
                />
                <audio id="audio" src={testMp3} ref={audioRef}/>
            </>
        )
    }
});

export default Player;